import requests

from emmobileapi import em_mission
import datetime
from LSTM.variableset import EMVar
from emmongo import em_mongomanager as mongoManager
import pandas as pd
import pymongo

class EnvFeel(object):

    SH_SZ_PCT = 'SH_SZ_PCT'
    SZ_SZ_PCT = 'SZ_SZ_PCT'
    ZDF_P3_PCT = 'ZDF_P3_PCT'
    ZDF_P10_PCT = 'ZDF_P10_PCT'
    YIMENG_PCT = 'YIMENG_PCT'

    WEIGHT_SH_SZ_PCT = 0.5
    WEIGHT_SZ_SZ_PCT = 0.5
    WEIGHT_ZDF_P3_PCT = 1
    WEIGHT_ZDF_P10_PCT = 2
    WEIGHT_YIMENG_PCT = 0.3

    # G_SH_SZ_PCT = {'factor_name'}

    def update_realtime_feel(self):
        t1 = datetime.datetime.now()
        # 上证上涨家数比率， 深圳上涨家数比率
        sh_sz_pct, sz_sz_pct = self.__dfcf()
        zd_p3_pct, zd_p10_pct = self.__zdf()
        yimeng_pct = self.__yimeng()
        ts = (datetime.datetime.now() - t1).total_seconds()
        print('刷新市场情绪:%d秒'%ts)

    def get_real_time_feel(self):
        r = mongoManager.db[mongoManager.COL_ENV_FEEL_FACTOR].find().sort('last_update_time', pymongo.DESCENDING)
        df = pd.DataFrame(list(r))
        t = df['real_time_value'] * df['real_time_weight']
        pct = t.sum() / df['real_time_weight'].sum()
        last_update_time = df['last_update_time'].ix[0]
        return pct, last_update_time

    def __dfcf(self):
        try:
            df = em_mission.dfcf()
            sh = df[df[EMVar.code] == EMVar.CODE_SH].iloc[-1]
            sh_sz_pct =  sh['sz_pct']
            self.__update_factor(factor_name=EnvFeel.SH_SZ_PCT, real_time_value=sh_sz_pct,
                                 real_time_weight=EnvFeel.WEIGHT_SH_SZ_PCT)
            sz = df[df[EMVar.code] == EMVar.CODE_SZ].iloc[-1]
            sz_sz_pct = sz['sz_pct']
            self.__update_factor(factor_name=EnvFeel.SZ_SZ_PCT, real_time_value=sz_sz_pct,
                                 real_time_weight=EnvFeel.WEIGHT_SZ_SZ_PCT)
            return sh_sz_pct, sz_sz_pct
        except Exception as e:
            print('ENV __dfcf() error')
            print(e)
            return 0, 0

    def __zdf(self):
        try:
            d = em_mission.zdf()
            zd_p3_pct = d['ZD_P3'] / (d['ZD_P3'] + d['ZD_M3'])
            self.__update_factor(factor_name=EnvFeel.ZDF_P3_PCT, real_time_value=zd_p3_pct,
                                 real_time_weight=EnvFeel.WEIGHT_ZDF_P3_PCT)
            zd_p10_pct = d['ZD_P10'] / (d['ZD_P10'] + d['ZD_M10'])
            self.__update_factor(factor_name=EnvFeel.ZDF_P10_PCT, real_time_value=zd_p10_pct,
                                 real_time_weight=EnvFeel.WEIGHT_ZDF_P10_PCT)
            return zd_p3_pct, zd_p10_pct
        except Exception as e:
            print('ENV __zdf() error')
            return 0, 0


    def __yimeng(self):
        try:
            position = em_mission.yimeng_position()
            self.__update_factor(factor_name=EnvFeel.YIMENG_PCT, real_time_value=position,
                                 real_time_weight=EnvFeel.WEIGHT_YIMENG_PCT)
            return position
        except Exception as e:
            print('ENV __yimeng() error')
            return 0


    def __update_factor(self, factor_name, real_time_value, real_time_weight=.0, default_weight=0, max_weight=0, min_weight=0, **kwargs):

        mongoManager.db[mongoManager.COL_ENV_FEEL_FACTOR].update_one({'factor_name': factor_name},
                                                                     {'$set': {'factor_name': factor_name,
                                                                      'real_time_value': real_time_value,
                                                                      'real_time_weight': real_time_weight,
                                                                      'default_weight': default_weight,
                                                                      'max_weight': max_weight,
                                                                      'min_weight': min_weight,
                                                                      'last_update_time':EMVar.format_now(EMVar.FORMATE_YMD_HMS)}}, upsert=True)

#dafdsf
# def ff():
#     import time
#     time.sleep(10)
#     print('d')
#
# def kk():
#     print('k')
#
# import threading
# e = EnvFeel()
#
# t = threading.Thread(target=ff())
# t.setDaemon(False)
# t.start()
# t = threading.Thread(target=kk())
# t.setDaemon(False)
# t.start()

e = EnvFeel()
e.update_realtime_feel()
e.get_real_time_feel()